package com.codegravity.mobile.expensms;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Gallery;

public class ChartsGallery extends Activity {

	private static final Exception DBExcep = new Exception();
	private Gallery gallery = null;
	private List<List<Float>> e_amntMasterlst = null;
	private List<List<Integer>> e_cntMasterlist = null;

	private SharedPreferences myPrefs;
	int count = 0;

	private Date end_date;

	private List<Float> expense_lst, expense_weekly, expense_mnth;
	List<Integer> expense_cnt;
	List<String> weeks;
	boolean isSun = true;
	int adjustWK = 0;
	Calendar calendar = Calendar.getInstance(Locale.US);
	int screenWidth;
	int screenHeight;
	private static DateFormat formatter;
	int temp;
	String tempStr;
	Date current_date;
	float week_expense = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		init();
		setContentView(R.layout.scroller);
		initGUI();
		ExpenseDataBase db;
		db = new ExpenseDataBase(getApplicationContext());
		db.open();
		Cursor cursor = db.fetchAllAlerts(ExpenseDataBase.EXPENSE_TABLE,
				ExpenseDataBase.EXPENSE_INT);
		try {
			chkCur(cursor);
			cursor.moveToFirst();
			calendar.setTimeInMillis(cursor.getLong(2));
			initExplst();
			initCal();
			temp = 7 - getCalendarDAY(Calendar.DAY_OF_WEEK);
			calendar.add(Calendar.DAY_OF_MONTH, temp);
			end_date = calendar.getTime();
			do {
				processRecord(cursor, db);
			} while (cursor.moveToNext());
			e_cntMasterlist.add(expense_cnt);
			e_amntMasterlst.add(expense_lst);
			calendar.setTime(current_date);
			temp = getCalendarDAY(Calendar.DAY_OF_WEEK);
			week_expense = week_expense / temp;
			expense_weekly.add(week_expense);
			calendar.setTime(end_date);
			getWeek();
			fetchMonthlyExpense(current_date, db);

			cursor.close();
			db.close();
			ImageAdapter adapt = new ImageAdapter(this,
					this.getLayoutInflater(), e_amntMasterlst, e_cntMasterlist,
					weeks, expense_weekly, expense_mnth);
			gallery.setAdapter(adapt);
		} catch (Exception e) {
		}
		gallery.setSelection(gallery.getCount() - 1);
	}

	private void processRecord(Cursor cursor, ExpenseDataBase db) {
		current_date = new Date(cursor.getLong(2));
		calendar.setTime(current_date);
		System.out.println("Current Date "+formatter.format(current_date));
		if (current_date.compareTo(end_date) <= 0) {
			int tempWk = getCalendarDAY(Calendar.DAY_OF_WEEK);
			expense_lst.set(tempWk - 1,
					expense_lst.get(tempWk - 1) + cursor.getFloat(1));
			week_expense = week_expense + cursor.getFloat(1);
			expense_cnt.set(tempWk - 1, expense_cnt.get(tempWk - 1) + 1);
		} else {
			e_cntMasterlist.add(expense_cnt);
			e_amntMasterlst.add(expense_lst);
			calendar.setTime(end_date);
			week_expense = week_expense / 7;
			expense_weekly.add(week_expense);
			week_expense = 0;
			getWeek();
			fetchMonthlyExpense(end_date, db);
			calendar.add(Calendar.DAY_OF_MONTH, 7);
			end_date = calendar.getTime();
			initExplst();
			cursor.moveToPrevious();
		}
	}

	private void fetchMonthlyExpense(Date current_date, ExpenseDataBase db) {
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		long monthStart = calendar.getTimeInMillis();
		calendar.setTime(current_date);
		long monthCurr = calendar.getTimeInMillis(); 

		Cursor cur_avg = db.fetchAllAlert(ExpenseDataBase.EXPENSE_TABLE,
				ExpenseDataBase.EXPENSE_INT, monthStart, monthCurr);
		float mnth_expense = 0;
		if (cur_avg.getCount() > 0) {
			cur_avg.moveToFirst();
			do {
				mnth_expense = mnth_expense + cur_avg.getFloat(1);
			} while (cur_avg.moveToNext());
		} 
		cur_avg.close();
		mnth_expense = mnth_expense / calendar.get(Calendar.DAY_OF_MONTH);
		expense_mnth.add(mnth_expense);
	}

	private void chkCur(Cursor cursor) throws Exception {
		if (cursor == null)
			throw DBExcep;
		count = cursor.getCount();
		if (count <= 0)
			throw DBExcep;
	}

	private void initExplst() {
		expense_lst = new ArrayList<Float>();
		expense_cnt = new ArrayList<Integer>();
		for (int i = 0; i < 7; i++) {
			expense_lst.add((float) 0);
			expense_cnt.add(0);
		}
	}

	private void getWeek() {
		calendar.add(Calendar.DAY_OF_MONTH, -6);
		tempStr = formatter.format(calendar.getTime()) + " to "
				+ formatter.format(end_date);
		System.out.println("Week "+tempStr);
		weeks.add(tempStr);
	}

	private void initCal() {
		calendar.set(Calendar.HOUR, calendar.getActualMaximum(Calendar.HOUR));
		calendar.set(Calendar.MINUTE,
				calendar.getActualMaximum(Calendar.MINUTE));
		calendar.set(Calendar.SECOND,
				calendar.getActualMaximum(Calendar.SECOND));
		calendar.set(Calendar.AM_PM, Calendar.PM);
	}

	private void initGUI() {
		Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();
		screenWidth = display.getWidth();
		screenHeight = display.getHeight();
		gallery = (Gallery) findViewById(R.id.mainviewGallery);
		gallery.getLayoutParams().width = screenWidth;
		gallery.getLayoutParams().height = screenHeight;
		gallery.setAnimationDuration(1000);
	}

	private void init() {
		myPrefs = getSharedPreferences("SMSExpense", MODE_WORLD_READABLE);
		isSun = myPrefs.getBoolean("weekSun", false);
		if (isSun)
			adjustWK = 0;
		else
			adjustWK = 1;
		e_cntMasterlist = new ArrayList<List<Integer>>();
		e_amntMasterlst = new ArrayList<List<Float>>();
		expense_weekly = new ArrayList<Float>();
		expense_mnth = new ArrayList<Float>();
		weeks = new ArrayList<String>();
		formatter = new SimpleDateFormat("dd/MM/yyyy");
	}

	int getCalendarDAY(int field) {
		if ((calendar.get(field) - adjustWK) != 0)
			return calendar.get(field) - adjustWK;
		else
			return 7;
	}
}
